const crypto = require('crypto');

const { Controller } = require('egg');

class WechatController extends Controller {
  async index() {
    const { query } = this.ctx.request;
    const signature = query.signature; // 获取微信发送参数的signature
    const timestamp = query.timestamp; // 获取微信发送参数的timestamp
    const nonce = query.nonce; // 获取微信发送参数的nonce
    const echostr = query.echostr;
    if (await this.check(timestamp, nonce, signature, '1234smr')) {
      this.ctx.body = echostr;
    } else {
      this.ctx.body = 'It is not from weixin';
    }
  }

  async check(timestamp, nonce, signature, token) {
    const tmp = [ token, timestamp, nonce ].sort().join('');
    const currSign = crypto.createHash('sha1').update(tmp).digest('hex');
    return (currSign === signature);
  }
  /**
   * 获取微信access_token
  */
  async getAccessToken() {
    const { ctx } = this;
    const data = await ctx.service.wechatService.getToken();
    ctx.body = {
      message: 'success',
      token: data,
    };
  }
  /**
   * 发送微信公众号模版信息
  */
  async sendTemplateMessage() {
    const { ctx } = this;
    const { openid } = ctx.request.body;
    if (!openid) {
      ctx.body = {
        message: 'openid is empty',
      };
      return false;
    }
    const body = await ctx.service.wechatService.sendMessage(openid, '4ScwYSfBakbCHR_eju0Co4TmWX_jcscU63A0Az74Xvg');
    ctx.body = body;
  }
}

module.exports = WechatController;
